package com.apes.fn.scm.purchaseReturn.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.purchaseReturn.model.PurchaseReturnApproval;
import com.apes.fn.scm.purchaseReturn.model.PurchaseReturnApprovalItem;
import com.apes.fn.scm.purchaseReturn.repository.PurchaseReturnApprovalRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.soe.metadata.Scene;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.account.model.InventoryBatch;
import com.apes.scm.account.account.model.Stock;
import com.apes.scm.account.account.repository.InventoryBatchRepository;
import com.apes.scm.account.account.repository.StockRepository;
import com.apes.scm.account.account.service.InventoryService;
import com.apes.scm.account.account.service.ProductAccountService;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.service.StoreService;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.repository.CategorySupplyRangeRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.pur.purchaseReturn.model.PurchaseReturn;
import com.apes.scm.rbac.repository.UserRepository;
import com.apes.scm.stock.transfer.model.Pick;
import com.apes.scm.stock.transfer.model.Transfer;
import com.apes.scm.stock.transfer.repository.PickRepository;
import com.apes.scm.voucher.service.VoucherType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.scm.purchaseReturn.service
 * @ClassName: PurchaseReturnApprovalService
 * @Author: pyb
 * @CreateTime: 2020-01-19 18:49
 * @Description: 返厂审批单服务
 * @Version: 1.0
 */
@Service("purchaseReturnApprovalService")
public class PurchaseReturnApprovalService extends DomainService {
    PurchaseReturnApprovalRepository purchaseReturnApprovalRepository;

    @Autowired
    private void setPurchaseReturnApprovalRepository(PurchaseReturnApprovalRepository purchaseReturnApprovalRepository) {
        this.purchaseReturnApprovalRepository = purchaseReturnApprovalRepository;
    }


    InventoryBatchRepository inventoryBatchRepository;

    @Autowired
    private void setInventoryBatchRepository(InventoryBatchRepository inventoryBatchRepository) {
        this.inventoryBatchRepository = inventoryBatchRepository;
    }

    StockRepository stockRepository;

    @Autowired
    private void setStockRepository(StockRepository stockRepository) {
        this.stockRepository = stockRepository;
    }

    LocationRepository locationRepository;

    @Autowired
    private void setLocationRepository(LocationRepository locationRepository) {
        this.locationRepository = locationRepository;
    }

    ProductAccountService productAccountService;

    @Autowired
    private void setProductAccountService(ProductAccountService productAccountService) {
        this.productAccountService = productAccountService;
    }


    StoreService storeService;

    @Autowired
    private void setStoreService(StoreService storeService) {
        this.storeService = storeService;
    }

    @Autowired
    InventoryService inventoryService;

    @Value("${apes.switched:false}")
    private Boolean switched;

    /**
     * 创建
     *
     * @param request
     * @return
     */
    public PurchaseReturnApproval save(SimpleRequest request) {
        PurchaseReturnApproval approval = request.getO(PurchaseReturnApproval.class);
        if (switched) {
            throw new RuntimeException("急件售后创建已被停用，不允许创建");
        }
        approval.setState("sent");
        //获取中转仓
        List<Location> locations = locationRepository.findAll(JpaDsl.toCriteriaByEq("usage.id", "8", "company.id", approval.getCompany().getId()));
        if (locations.size() <= 0) {
            throw new RuntimeException("未获取到中转仓！请先定义退货中转仓");
        }
        approval.setTurnoverLocation(locations.stream().findAny().get());
        storeService.judgeFCKBJ(approval.getShipLocation());
        storeService.judgeFCKBJ(approval.getTurnoverLocation());
        approval = purchaseReturnApprovalRepository.saveAndFlush(approval);
        //更新库存 批次
        updateProductAvailableAndBatch(approval, false, "返厂申请保存");
        return approval;
    }

    /**
     * 编辑
     *
     * @param request
     * @return
     */
    public PurchaseReturnApproval update(SimpleRequest request) {
        PurchaseReturnApproval approval = request.getO(PurchaseReturnApproval.class);
        storeService.judgeFCKBJ(approval.getShipLocation());
        storeService.judgeFCKBJ(approval.getTurnoverLocation());
        PurchaseReturnApproval validOrder = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        if ((int) request.get("version") != validOrder.getVersion())
            throw new RuntimeException("急件售后申请单已发生改变,请重新查询急件售后申请单状态！");
        // 还原商品可用数，减少商品批次冻结数量
        updateProductAvailableAndBatch(validOrder, true, "返厂申请还原");
        PurchaseReturnApproval purchaseReturnApproval = purchaseReturnApprovalRepository.saveAndFlush(approval);
        //下库存 批次
        updateProductAvailableAndBatch(purchaseReturnApproval, false, "返厂申请编辑");
        return purchaseReturnApproval;
    }

    /**
     * 审核
     *
     * @param request
     * @return
     */
    public PurchaseReturnApproval approval(SimpleRequest request) {
        PurchaseReturnApproval approval = request.getO(PurchaseReturnApproval.class);
        approval.setState("oa");
        approval.setApproveUid(this.getPerson(request));
        approval.setDateApprove(new Date());
        approval.getPurchaseReturnApprovalItems().forEach(purchaseReturnApprovalItem -> purchaseReturnApprovalItem.setProductReturnQtyApprove(purchaseReturnApprovalItem.getProductReturnQty()));
        return purchaseReturnApprovalRepository.saveAndFlush(approval);
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        PurchaseReturnApproval approval = request.getO(PurchaseReturnApproval.class);
        // 还原商品可用数，减少商品批次冻结数量
        updateProductAvailableAndBatch(approval, true, "返厂申请保存");
        purchaseReturnApprovalRepository.delete(approval);
        return "删除成功";
    }

    /**
     * 根据单号查询
     *
     * @param request
     * @return
     */
    public PurchaseReturnApproval find(SimpleRequest request) {
        return purchaseReturnApprovalRepository.findOne(JpaDsl.toCriteriaByEq("applyDocument", (String) request.get("id"))).get();
    }

    /**
     * 返厂申请 处理
     *
     * @param request
     * @return PurchaseReturnApproval
     */
    public PurchaseReturnApproval handle(SimpleRequest request) {
        PurchaseReturnApproval purchaseReturnApproval = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        purchaseReturnApproval.setPurchaseApproveUid(this.getPerson(request));
        purchaseReturnApproval.setDatePurchaseApprove(new Date());
        purchaseReturnApproval.setState("disposing");
        PurchaseReturnApproval validOrder = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        if ((int) request.get("version") != validOrder.getVersion())
            throw new RuntimeException("急件售后申请单已发生改变,请重新查询急件售后申请单状态！");
        updateProductAvailable(validOrder, true, "返厂申请还原可用数");
        return generateStockTransfer(purchaseReturnApproval, true);
    }

    /**
     * 检查物流
     *
     * @param request
     * @return
     */
    public void checkLogistics(SimpleRequest request) {
        PurchaseReturnApproval purchaseReturnApproval = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        List<Pick> picks = SpringManager.getBean(PickRepository.class).findAll(JpaDsl.toCriteriaByEq("origin", purchaseReturnApproval.getDerivedDocument(), "location", purchaseReturnApproval.getShipLocation()));
//        Optional<Pick> pickOptional = SpringManager.getBean(PickRepository.class).findOne(JpaDsl.toCriteriaByEq("origin", purchaseReturnApproval.getDerivedDocument(), "location", purchaseReturnApproval.getShipLocation()));
        if (/*!pickOptional.isPresent()*/picks.size() == 0) {
            throw new RuntimeException("交货单尚未创建，请等待或检查转储单:" + purchaseReturnApproval.getDerivedDocument());
        }
        picks.forEach(pick -> {
            if (!"done".equals(pick.getState())) throw new RuntimeException("门店未交货，无法鉴定，请先取货");
        });
       /* if (!"done".equals(pickOptional.get().getState())) {
            throw new RuntimeException("门店未交货，无法鉴定，请先取货");
        }*/
       /* Optional<Pick> optionalPick = SpringManager.getBean(PickRepository.class).findOne(JpaDsl.toCriteriaByEq("origin", purchaseReturnApproval.getDerivedDocument(), "location", purchaseReturnApproval.getTurnoverLocation()));
        if (!optionalPick.isPresent()) {
            throw new RuntimeException("交货单尚未创建，请等待或检查转储单:" + purchaseReturnApproval.getDerivedDocument());
        }
        if (!"done".equals(optionalPick.get().getState())) {
            throw new RuntimeException("中转站未收货，无法鉴定，请先收货");
        }*/
        List<Pick> receiptPick = SpringManager.getBean(PickRepository.class).findAll(JpaDsl.toCriteriaByEq("origin", purchaseReturnApproval.getDerivedDocument(), "location", purchaseReturnApproval.getTurnoverLocation()));
        if (receiptPick.size() == 0) {
            throw new RuntimeException("交货单尚未创建，请等待或检查转储单:" + purchaseReturnApproval.getDerivedDocument());
        }
        receiptPick.forEach(pick -> {
            if (!"done".equals(pick.getState())) throw new RuntimeException("中转站未收货，无法鉴定，请先收货");
        });
    }

    /**
     * 采购审核 同意
     *
     * @param request
     * @return
     */
    public PurchaseReturnApproval purchaseApprove(SimpleRequest request) {
        PurchaseReturnApproval approval = request.getO(PurchaseReturnApproval.class);
        String processing = processing(request);
        if (processing != null) {
            approval.setCallbackDocument(processing);
        }
        approval.setState("consent");
        purchaseReturnApprovalRepository.saveAndFlush(approval);
        return approval;
    }


    /**
     * 驳回
     *
     * @param request
     * @return PurchaseReturnApproval
     */
    public PurchaseReturnApproval reject(SimpleRequest request) {
        PurchaseReturnApproval purchaseReturnApproval = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        purchaseReturnApproval.setPurchaseApproveUid(this.getPerson(request));
        purchaseReturnApproval.setDatePurchaseApprove(new Date());
        purchaseReturnApproval.setState("cancel");
        PurchaseReturnApproval validOrder = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        if ((int) request.get("version") != validOrder.getVersion())
            throw new RuntimeException("急件售后申请单已发生改变,请重新查询急件售后申请单状态！");
        long count = purchaseReturnApproval.getPurchaseReturnApprovalItems().stream().filter(
                (purchaseReturnApprovalItem) -> "A1001".equals(purchaseReturnApprovalItem.getSupplier().getId())).count();
        if (count != 0) {
            throw new RuntimeException("车宝供货(A1001)的商品不允许拒收");
        }
        updateProductBatch(validOrder, true, "中转站驳回还原批次");
        return generateStockTransfer(purchaseReturnApproval, false);
    }


    /**
     * 拒绝返厂
     *
     * @param request
     * @return
     */
    public PurchaseReturnApproval refuse(SimpleRequest request) {
        PurchaseReturnApproval purchaseReturnApproval = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        purchaseReturnApproval.setPurchaseApproveUid(this.getPerson(request));
        purchaseReturnApproval.setDatePurchaseApprove(new Date());
        purchaseReturnApproval.setState("cancel");
        PurchaseReturnApproval validOrder = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        if ((int) request.get("version") != validOrder.getVersion())
            throw new RuntimeException("急件售后申请单已发生改变,请重新查询急件售后申请单状态！");
        // 还原商品可用数，减少商品批次冻结数量
        updateProductAvailableAndBatch(validOrder, true, "返厂申请保存");
        return purchaseReturnApprovalRepository.saveAndFlush(purchaseReturnApproval);
    }

    /**
     * 财务审核
     *
     * @param request
     * @return
     */
    public PurchaseReturnApproval financialAudit(SimpleRequest request) {
        PurchaseReturnApproval purchaseReturnApproval = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        PurchaseReturnApproval validOrder = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        if ((int) request.get("version") != validOrder.getVersion())
            throw new RuntimeException("急件售后申请单已发生改变,请重新查询急件售后申请单状态！");
        updateProductBatch(validOrder, true, "财务审核还原可用数");

        Map<PartyRole, Map<InventoryBatch, List<PurchaseReturnApprovalItem>>> contractMapMap = purchaseReturnApproval.getPurchaseReturnApprovalItems().stream().collect(
                Collectors.groupingBy(item -> item.getSupplier(),
                        Collectors.groupingBy(item -> item.getInventoryBatch())));

        Enumeration moveType = new Enumeration();
        moveType.setId("one");
        //生成返厂订单 并回填返厂单号
        contractMapMap.forEach((srupplier, y) -> {
            y.forEach((k, v) -> {
                JSONArray purchaseReturnItems = new JSONArray();
                v.forEach(item -> {
                    JSONObject object = new JSONObject();
                    object.put("product", mapper("id", item.getProduct().getId()));
                    object.put("tax", mapper("id", item.getInventoryBatch().getTax().getId()));
                    object.put("inventoryBatch", mapper("id", item.getInventoryBatch().getId()));
                    object.put("uom", mapper("id", item.getUom().getId()));
                    object.put("productSumQty", item.getProductSumQty());
                    object.put("priceUnit", item.getPriceUnit());
                    object.put("productReturnQty", item.getProductReturnQtyApprove());
                    purchaseReturnItems.add(object);

                });
                String operator = purchaseReturnApproval.getPurchaseApproveUid().getId();
                String userId = SpringManager.getBean(UserRepository.class).findAll(JpaDsl.toCriteriaByEq("person.id", operator)).get(0).getId().toString();
                PurchaseReturn purchaseReturn = invoke("purchase.return.create", mapper("scene", mapper("id", "PR001"),
                        "origin", purchaseReturnApproval.getId(), "originBusinessType", purchaseReturnApproval.getInnerBusinessType(),
                        "auto", Objects.equals(VoucherType.SUPPLIER_CODE, srupplier.getId()),
                        "company", mapper("id", purchaseReturnApproval.getCompany().getId()),
                        "dept", mapper("id", v.stream().findFirst().get().getInventoryBatch().getDept().getId()), "clerk", mapper("id", this.getPersonId(request)), "supplier", mapper("id", srupplier.getId()),
                        "contract", k.getContract() != null ? mapper("id", k.getContract().getId()) : new HashMap<>(),
                        "cooperation", mapper("id", k.getCooperation().getId()),
                        "moveType", mapper("id", moveType.getId()), "location", mapper("id", purchaseReturnApproval.getTurnoverLocation().getId()),
                        "note", purchaseReturnApproval.getNote(),
                        "purchaseReturnItems", purchaseReturnItems, "createUid", mapper("id", request.getPersonId())));


                purchaseReturn.setUserId(userId);
                purchaseReturn.setUpdater(purchaseReturnApproval.getPurchaseApproveUid().getId());
                purchaseReturn.setApproveUid(purchaseReturnApproval.getPurchaseApproveUid());
               invoke("purchase.return.approve", MapUtil.mapped(purchaseReturn));
               List<Long> ids = v.stream().map(PurchaseReturnApprovalItem::getId).collect(Collectors.toList());
                purchaseReturnApproval.getPurchaseReturnApprovalItems().forEach(item -> {
                    if (ids.indexOf(item.getId()) >= 0) {
                        item.setPurchaseReturnId(purchaseReturn.getId());
                    }
                });
            });

        });
        purchaseReturnApproval.setState("approve");
        purchaseReturnApproval.setFinanceApproveUid(this.getPerson(request));
        purchaseReturnApproval.setDateFinanceApprove(new Date());
        return purchaseReturnApprovalRepository.saveAndFlush(purchaseReturnApproval);
    }

    /**
     * 返厂处理
     *
     * @param request
     * @param request
     */
    public String processing(SimpleRequest request) {
        //鉴定后急件售后申请单
        PurchaseReturnApproval returnApproval = request.getO(PurchaseReturnApproval.class);
        //鉴定前急件售后申请单
        PurchaseReturnApproval purchaseReturnApproval = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        //取2个item
        Map<Long, PurchaseReturnApprovalItem> applyItemMap = purchaseReturnApproval.getPurchaseReturnApprovalItems().stream().collect(Collectors.toMap(PurchaseReturnApprovalItem::getId, item -> item));
        Map<Long, PurchaseReturnApprovalItem> itemMap = returnApproval.getPurchaseReturnApprovalItems().stream().collect(Collectors.toMap(PurchaseReturnApprovalItem::getId, item -> item));

        //回调商品
        JSONArray transferItems = new JSONArray();
        applyItemMap.forEach((k, v) -> {
            double productReturnQtyApprove = v.getProductReturnQtyApprove();
            double qtyApprove = itemMap.get(k).getProductReturnQtyApprove();
            //当该商品同意返厂数量 与返厂数量不一致
            if (productReturnQtyApprove != qtyApprove) {
                if (productReturnQtyApprove < qtyApprove) {
                    throw new RuntimeException("同意返厂数量不得大于返厂数量");
                }
                //退还门店 productReturnQtyApprove - qtyApprove
                JSONObject transfer = new JSONObject();
                transfer.put("product", mapper("id", v.getProduct().getId()));
                transfer.put("uom", mapper("id", v.getUom().getId()));
                transfer.put("transferQty", productReturnQtyApprove - qtyApprove);
                transfer.put("note", v.getNote());
                transferItems.add(transfer);
            }

        });
        if (transferItems.size() > 0) {
            //生成回调转储单并审核
            String transferType = "";
            if (purchaseReturnApproval.getTurnoverLocation().getDepot().getId().equals(purchaseReturnApproval.getShipLocation().getDepot().getId())) {
                transferType = "000164";
            } else {
                transferType = "000165";
            }
            Transfer invoke = invoke("stock.transfer.create", mapper(
                    "originLocation", mapper("id", purchaseReturnApproval.getTurnoverLocation().getId()),
                    "usage", mapper("id", purchaseReturnApproval.getTurnoverLocation().getUsage().getId()),
                    "receiptLocation", mapper("id", purchaseReturnApproval.getShipLocation().getId()),
                    "transferType", mapper("id", transferType), "note", "急件售后申请单转储出库", "reason", mapper("id", "000184"),
                    "scene", mapper("id", "PT001"), "transferItems", transferItems, "origin", returnApproval.getId(), "originBusinessType", "PurchaseReturnApply",
                    "source", purchaseReturnApproval.getId(),
                    "sourceBusinessType", purchaseReturnApproval.getInnerBusinessType(),
                    "sourceBusinessTypeName", "急件售后申请单"
            ));
            Transfer transfer = invoke("stock.transfer.approve", MapUtil.mapped(invoke));
            return transfer.getId();
        }
        return null;
    }

    /**
     * 生成转储单并审核
     * sign true 下发 false 回调
     *
     * @param approval
     * @return
     */
    public PurchaseReturnApproval generateStockTransfer(PurchaseReturnApproval approval, boolean sign) {
        PurchaseReturnApproval purchaseReturnApproval = purchaseReturnApprovalRepository.saveAndFlush(approval);
        //生成转储订单
        Enumeration transferType = new Enumeration();
        if (sign) {
            transferType.setId("000159");
        } else {
            transferType.setId("000160");
        }
        Enumeration reason = new Enumeration();
        reason.setId("000184");
        Scene scene = new Scene();
        scene.setId("PT001");
        JSONArray transferItems = new JSONArray();
        approval.getPurchaseReturnApprovalItems().forEach(item -> {
            JSONObject transfer = new JSONObject();
            transfer.put("product", mapper("id", item.getProduct().getId()));
            transfer.put("uom", mapper("id", item.getUom().getId()));
            transfer.put("transferQty", item.getProductReturnQty());
            transfer.put("note", item.getNote());
            transferItems.add(transfer);
        });
        //生成转储订单
        Transfer invoke = invoke("stock.transfer.create", mapper(
                "company", mapper("id", approval.getCompany().getId()), "originLocation", mapper("id", sign ? approval.getShipLocation().getId() : approval.getTurnoverLocation().getId()),
                "usage", mapper("id", sign ? approval.getShipLocation().getUsage().getId() : approval.getTurnoverLocation().getUsage().getId()),
                "receiptLocation", mapper("id", sign ? approval.getTurnoverLocation().getId() : approval.getShipLocation().getId()),
                "transferType", mapper("id", transferType.getId()), "note", "急件售后申请单转储出库", "reason", mapper("id", reason.getId()),
                "scene", mapper("id", scene.getId()), "transferItems", transferItems, "origin", approval.getId(), "originBusinessType", "PurchaseReturnApply",
                "source", purchaseReturnApproval.getId(),
                "sourceBusinessType", purchaseReturnApproval.getInnerBusinessType(),
                "sourceBusinessTypeName", "急件售后申请单"
        ));
        //审核
        Transfer transfer = invoke("stock.transfer.approve", MapUtil.mapped(invoke));
        //添加转储单据号
        if (sign) {
            purchaseReturnApproval.setDerivedDocument(transfer.getId());
        } else {
            purchaseReturnApproval.setCallbackDocument(transfer.getId());
        }
        return purchaseReturnApprovalRepository.saveAndFlush(purchaseReturnApproval);
    }

    /**
     * 结束流程
     *
     * @param request
     * @return
     */
    public PurchaseReturnApproval transEnd(SimpleRequest request) {
        PurchaseReturnApproval purchaseReturnApproval = purchaseReturnApprovalRepository.findOne((String) request.get("id"));
        purchaseReturnApproval.setState("done");
        return purchaseReturnApprovalRepository.saveAndFlush(purchaseReturnApproval);
    }

    /**
     * 查找可退商品批次(全部供应商)
     *
     * @param simpleRequest
     * @return Page<InventoryBatch>
     */
    public Page<InventoryBatch> findInventory(SimpleRequest simpleRequest) {
        String productId = simpleRequest.get("productId");
        String locationId = simpleRequest.get("locationId");
        // 查找商品库存帐的可用数是否大于0
        Stock stock = stockRepository.findFirstByProductIdAndLocationIdAndUsableQtyGreaterThan(productId, locationId, 0);
        // 获取可用数
        double usableQty = Optional.ofNullable(stock).map(Stock::getUsableQty).orElseThrow(() -> new RuntimeException("商品库存帐不满足退货条件！"));
        String companyId = simpleRequest.get("companyId");
        // 获取结存大于冻结的批次
        Page<InventoryBatch> inventoryBatchPage = inventoryBatchRepository.findReturnableByCompanyIdAndProductIdNotInSupplierId(companyId, productId, PageRequest.of(simpleRequest.get("page"), simpleRequest.get("size")));
        inventoryBatchPage.getContent().forEach(
                (inventoryBatch) -> {
                    inventoryBatch.setUsableQty(usableQty);
                    inventoryBatch.setCanReturnQty(Math.min(usableQty, inventoryBatch.getBalanceQty() - inventoryBatch.getFrostQty()));
                }
        );
        return inventoryBatchPage;
    }


    /**
     * 更新商品库存可用数，批次表冻结数量
     *
     * @param purchaseReturnApproval
     * @param flag
     * @param note
     */
    private void updateProductAvailableAndBatch(PurchaseReturnApproval purchaseReturnApproval, boolean flag, String note) {
        purchaseReturnApproval.getPurchaseReturnApprovalItems().forEach(item -> {
            //退货数量
            double changeQty = Math.abs(item.getProductReturnQty());
            if (!flag) {
                changeQty = -1 * changeQty;
            }
            if (LogicalUtil.notIn(item.getProduct().getType(), "aut")) {
                // 减少（增加）商品可用数
                productAccountService.setProductAvailable(item.getProduct(), purchaseReturnApproval.getShipLocation(),
                        item.getUom(), changeQty, purchaseReturnApproval.getInnerBusinessType(), purchaseReturnApproval.getInnerBusinessKey(),
                        String.valueOf(item.getId()), note, purchaseReturnApproval.getCompany());
            }
            // 增加（减少）商品价值（商品批次） 的冻结数量
            // 查询批次信息
            InventoryBatch inventoryBatch = inventoryBatchRepository.findOne(item.getInventoryBatch().getId());
            //inventoryBatch.changeFrostQty(-1 * changeQty);
            inventoryService.changeFrostQty(inventoryBatch, item.getUom(),-1 * changeQty, purchaseReturnApproval.getCompany(), purchaseReturnApproval.getInnerBusinessType(), purchaseReturnApproval.getInnerBusinessKey(),
                    String.valueOf(item.getId()), note);
        });
    }

    /**
     * 更新商品库存可用数
     *
     * @param purchaseReturnApproval
     * @param flag
     * @param note
     */
    private void updateProductAvailable(PurchaseReturnApproval purchaseReturnApproval, boolean flag, String note) {
        purchaseReturnApproval.getPurchaseReturnApprovalItems().forEach(purchaseReturnApprovalItem -> {
            //退货数量
            double changeQty = Math.abs(purchaseReturnApprovalItem.getProductReturnQty());
            if (!flag) {
                changeQty = -1 * changeQty;
            }
            if (LogicalUtil.notIn(purchaseReturnApprovalItem.getProduct().getType(), "aut")) {
                // 减少（增加）商品可用数
                productAccountService.setProductAvailable(purchaseReturnApprovalItem.getProduct(), purchaseReturnApproval.getShipLocation(),
                        purchaseReturnApprovalItem.getUom(), changeQty, purchaseReturnApproval.getInnerBusinessType(), purchaseReturnApproval.getInnerBusinessKey(),
                        String.valueOf(purchaseReturnApprovalItem.getId()), note, purchaseReturnApproval.getCompany());
            }

        });
    }

    /**
     * 更新商品批次表冻结数量
     *
     * @param purchaseReturnApproval
     * @param flag
     * @param note
     */
    private void updateProductBatch(PurchaseReturnApproval purchaseReturnApproval, boolean flag, String note) {
        purchaseReturnApproval.getPurchaseReturnApprovalItems().forEach(item -> {
            //退货数量
            double changeQty = Math.abs(item.getProductReturnQty());
            if (!flag) {
                changeQty = -1 * changeQty;
            }
            // 增加（减少）商品价值（商品批次） 的冻结数量
            // 查询批次信息
            InventoryBatch inventoryBatch = inventoryBatchRepository.findOne(item.getInventoryBatch().getId());
            //  增加（减少）冻结数量
            //inventoryBatch.changeFrostQty(-1 * changeQty);
            inventoryService.changeFrostQty(inventoryBatch, item.getUom(),-1 * changeQty,purchaseReturnApproval.getCompany(), purchaseReturnApproval.getInnerBusinessType(), purchaseReturnApproval.getInnerBusinessKey(),
                    String.valueOf(item.getId()), note);
        });
    }
}
